﻿using System.Collections.Generic;
using EnetaMvc.Core.Domain.Content;
using EnetaMvc.Core.Repositories;
using EnetaMvc.Infrastructure;
using NHibernate;
using NHibernate.Criterion;

namespace EnetaMvc.Data.NHibernate.Repositories
{
    public class TagRepository : BaseRepository, ITagRepository
    {
        private readonly ISession _session;

        public TagRepository(IMapperSession session) : base(((NHSession)session).GetCurrentSession())
        {
            _session = ((NHSession)session).GetCurrentSession();
        }

        public IList<Tag> ListTags()
        {
            return _session.CreateCriteria<Tag>().List<Tag>();
        }

        public Tag GetTagById(long id)
        {
            return _session.Get<Tag>(id);
        }


        public void SaveTag(Tag tag)
        {
            SaveInTransaction(tag);
        }

        public void DeleteTag(long id)
        {
            Tag tag = GetTagById(id);
            if (tag == null)
                return;

            DeleteInTransaction(tag);
        }


        public IList<Tag> ListTagsByGroupId(long tagGroupId)
        {
            var criteria = _session.CreateCriteria<Tag>()
                            .CreateCriteria("Group").Add(Expression.Eq("Id", tagGroupId));
            return criteria.List<Tag>();
        }
    }
}
